package com.efast.dmom.equipment.opc.client;

import java.net.UnknownHostException;
import java.util.concurrent.Executors;

import org.jinterop.dcom.common.JIException;
import org.openscada.opc.dcom.da.OPCSERVERSTATE;
import org.openscada.opc.lib.common.AlreadyConnectedException;
import org.openscada.opc.lib.common.ConnectionInformation;
import org.openscada.opc.lib.da.Server;

public class OPCConnector {

	private static ConnectionInformation ci;
	private static Server server;
	private static OPCGroupBuilder groupBuilder = null;
	private static OPCConnector connector = null;

	private OPCConnector() {
		if (groupBuilder == null) {
			groupBuilder = new OPCGroupBuilder();
		}
	}

	public static OPCConnector getInstance() {

		if (connector == null) {
			connector = new OPCConnector();
			initConnection();
		}
		return connector;
	}

	public OPCGroupBuilder getGroupBuilder() {
		return groupBuilder;
	}

	public boolean checkConnection() {

		boolean connected = true;
		try {
			OPCSERVERSTATE status = server.getServerState(0).getServerState();
			connected = OPCSERVERSTATE.OPC_STATUS_RUNNING == status ? true : false;
		} catch (Throwable e) {
			e.printStackTrace();
			connected = false;
		}
		return connected;
	}

	protected static void initConnection() {

		ci = OPCConfiguration.getCLSIDConnInfo();

		server = new Server(ci, Executors.newSingleThreadScheduledExecutor());
		try {
			server.connect();
			groupBuilder.buildGroup(server);

		} catch (IllegalArgumentException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (UnknownHostException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (JIException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (AlreadyConnectedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	protected Server getServer() {
		return server;
	}
}
